﻿using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Web.UI;
using shfa.snomtastic.admin.components;
using shfa.snomtastic.data;
using shfa.snomtastic.data.business;
using shfa.snomtastic.data.security;
using Telerik.Web.UI;


namespace shfa.snomtastic.admin.editcontrols
{
    public partial class eUser : EditBase
    {
        #region Public Members

        public bool IsNewItem
        {
            get { return (ActiveItemId == Guid.Empty); }
        }

        public Guid ActiveItemId
        {
            get { return (hfItemId.Value != string.Empty) ? new Guid(hfItemId.Value) : Guid.Empty; }
            set { hfItemId.Value = value.ToString(); }
        }

        public AppConfig ac = new AppConfig();

        #endregion

        protected void Page_Load(object sender, EventArgs e) { }

        protected void Page_Init(object sender, EventArgs e)
        {

            if (ItemId != Guid.Empty)
                ActiveItemId = ItemId;

            if (ActiveItemId != Guid.Empty)
            {
                bindItem();
            }
            else
            {
                bindLists(new UserInfo());

            }

        }


        protected void bindItem()
        {
            UserController uc = new UserController();
            UserInfo ui = uc.SelectUser(ActiveItemId);
            if (ui != null)
            {
                lblHeaderLeft.Text = "User - " + ui.UserName;
                lblHeaderRight.Text = "";
                ddUser.Enabled = false;
                lblPasswordUpdate.Text = common.LongDateTime(ui.PasswordUpdate);
                lblPasswordUpdateAD.Text = common.LongDateTime(ui.PasswordUpdateAD);
                lblCreatedDate.Text = common.LongDateTime(ui.CreatedDate);
                lblUpdatedDate.Text = common.LongDateTime(ui.UpdatedDate);
                lblLastAccessDate.Text = common.LongDateTime(ui.LastAccessDate);


                bindLists(ui);
            }

        }

        protected void bindLists(UserInfo ui)
        {
            bindGroups(ui.GroupId);
            bindUsersFromAD(ui.UserName);
        }

        protected void bindGroups(Guid GroupId)
        {
            GroupController gc = new GroupController();
            List<GroupInfo> giList = gc.SelectGroups("Name Asc");
            ddGroups.DataSource = giList;
            ddGroups.DataValueField = "GroupId";
            ddGroups.DataTextField = "Name";
            ddGroups.DataBind();

            foreach (RadComboBoxItem item in ddGroups.Items)
            {
                item.ImageUrl = "~/images/icons/group.png";
            }

            if (ddGroups.FindItemByValue(GroupId.ToString()) != null)
            {
                ddGroups.FindItemByValue(GroupId.ToString()).Selected = true;
            }
        }

        protected void bindUsersFromAD(string UserName)
        {

            try
            {

                RijndaelEnhanced re = new RijndaelEnhanced();

                string adRoot = ac.Items["adRoot"];
                string adLogin = ac.Items["adLogin"];


                string adPassword = re.Decrypt(ac.Items["adPassword"]);

                DirectoryEntry dentry = new DirectoryEntry(adRoot, adLogin, adPassword);
                DirectorySearcher dsearcher = new DirectorySearcher(dentry);
                dsearcher.PageSize = 1000;
                dsearcher.PropertiesToLoad.Add("cn");
                dsearcher.PropertiesToLoad.Add("userPrincipalName");

                dsearcher.Filter = (ac.Items["adFilter"]);
                SearchResultCollection src = dsearcher.FindAll();
                foreach (SearchResult sr in src)
                {
                    try
                    {
                        RadComboBoxItem r = new RadComboBoxItem
                        {
                            Value = sr.Properties["userPrincipalName"][0].ToString(),
                            Text = sr.Properties["userPrincipalName"][0].ToString(),
                            ImageUrl = "~/images/icons/user.png",
                        };
                        ddUser.Items.Add(r);
                    }
                    catch { }
                }

                ddUser.Sort = RadComboBoxSort.Ascending;
                ddUser.SortItems();

                if (ddUser.FindItemByValue(UserName) != null)
                {
                    ddUser.FindItemByValue(UserName).Selected = true;
                }

            }
            catch { }

        }

        #region Action Event Helpers

        private void SaveItem()
        {
            if (Page.IsValid)
            {
                UserController uc = new UserController();
                UserInfo ui = new UserInfo();

                RijndaelEnhanced re = new RijndaelEnhanced();

                if (!IsNewItem)
                {
                    ui = uc.SelectUser(ActiveItemId);
                }

                ui.UserName = ddUser.SelectedItem.Text;
                ui.GroupId = new Guid(ddGroups.SelectedValue);
                ui.UpdatedDate = DateTime.UtcNow;

                if (txtPassword.Text != string.Empty)
                    ui.Password = re.Encrypt(txtPassword.Text);


                if (IsNewItem)
                {
                    ui.CreatedDate = DateTime.UtcNow;
                    if (ui.Password != string.Empty)
                        ui.PasswordUpdate = DateTime.UtcNow;

                    uc.InsertUser(ui);

                }
                else
                {
                    uc.UpdateUser(ui);
                }

                RaiseNavEvent(this, new NavEventArgs("eUsers", ActiveItemId));
            }


        }

        private void DeleteItem()
        {
            UserController uc = new UserController();
            uc.DeleteUser(ActiveItemId);
            RaiseNavEvent(this, new NavEventArgs("eUsers", ActiveItemId));
        }

        #endregion

        #region EditBase

        public override void EditBase_ActionEvent(object sender, ActionClickArgs e)
        {
            switch (e.ActionName)
            {
                case "Save":
                    SaveItem();
                    break;
                case "Delete":
                    DeleteItem();
                    break;
                case "Return":
                    RaiseNavEvent(this, new NavEventArgs("eUsers", ActiveItemId));
                    break;
                default:
                    break;
            }
        }

        public override List<ActionInfo> ActionList
        {
            get
            {
                List<ActionInfo> al = new List<ActionInfo>();
                al.Add(new ActionInfo("Save", "Save User", "~/images/icons/save.png", "", true, true));
                al.Add(new ActionInfo("Delete", "Delete User", "~/images/icons/delete.png", "Are you sure you want to delete this User", !IsNewItem));
                al.Add(new ActionInfo("Return", "Return", "~/images/icons/undo.png"));
                return al;
            }
        }

        #endregion

    }
}